// Base64 Encoder 渲染器
window.Base64EncoderRenderer = class Base64EncoderRenderer {
    static getHTML() {
        return `
            <div class="flex items-center justify-between mb-6">
                <h2 class="text-3xl font-bold text-gray-800">Base64 编解码工具</h2>
                <div class="flex items-center space-x-4">
                    <div class="text-sm text-gray-500">
                        <span id="base64-status" class="font-medium">就绪</span>
                    </div>
                </div>
            </div>

            <!-- 模式选择 -->
            <div class="bg-gray-50 border rounded-lg p-4 mb-6">
                <div class="flex items-center space-x-6 mb-4">
                    <label class="inline-flex items-center">
                        <input type="radio" class="form-radio text-blue-600" name="base64-mode" value="text" checked>
                        <span class="ml-2 font-medium">文本编解码</span>
                    </label>
                    <label class="inline-flex items-center">
                        <input type="radio" class="form-radio text-blue-600" name="base64-mode" value="file">
                        <span class="ml-2 font-medium">文件编解码</span>
                    </label>
                </div>
                
                <!-- 工具栏 -->
                <div class="flex flex-wrap items-center gap-3">
                    <button id="encode-base64" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center">
                        <i data-feather="lock" class="w-4 h-4 mr-2"></i>
                        编码
                    </button>
                    <button id="decode-base64" class="bg-green-600 hover:bg-green-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center">
                        <i data-feather="unlock" class="w-4 h-4 mr-2"></i>
                        解码
                    </button>
                    <button id="validate-base64" class="bg-purple-600 hover:bg-purple-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center">
                        <i data-feather="check-circle" class="w-4 h-4 mr-2"></i>
                        验证
                    </button>
                    
                    <div class="ml-auto flex items-center space-x-3">
                        <button id="clear-base64" class="bg-gray-200 hover:bg-gray-300 text-gray-700 font-bold py-2 px-4 rounded-lg transition duration-200">
                            清空
                        </button>
                        <button id="copy-base64" class="bg-gray-200 hover:bg-gray-300 text-gray-700 font-bold py-2 px-4 rounded-lg transition duration-200">
                            复制结果
                        </button>
                        <button id="download-base64" class="bg-gray-600 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200">
                            下载
                        </button>
                    </div>
                </div>
                
                <!-- 高级选项 -->
                <div class="flex flex-wrap items-center gap-4 mt-4 text-sm">
                    <div class="flex items-center space-x-2">
                        <label for="base64-charset">字符集:</label>
                        <select id="base64-charset" class="border rounded px-2 py-1 text-sm">
                            <option value="utf-8" selected>UTF-8</option>
                            <option value="ascii">ASCII</option>
                        </select>
                    </div>
                    <div class="flex items-center space-x-2">
                        <input type="checkbox" id="base64-url-safe" class="form-checkbox">
                        <label for="base64-url-safe">URL安全编码</label>
                    </div>
                    <div class="flex items-center space-x-2">
                        <input type="checkbox" id="base64-remove-padding" class="form-checkbox">
                        <label for="base64-remove-padding">移除填充字符</label>
                    </div>
                </div>
            </div>

            <!-- 错误/成功提示 -->
            <div id="base64-error" class="hidden bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded-lg mb-4">
                <div class="flex items-center">
                    <i data-feather="alert-circle" class="w-5 h-5 mr-2 text-red-500"></i>
                    <div>
                        <span class="font-medium">处理失败：</span>
                        <span id="base64-error-message"></span>
                    </div>
                </div>
            </div>

            <div id="base64-success" class="hidden bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded-lg mb-4">
                <div class="flex items-center">
                    <i data-feather="check-circle" class="w-5 h-5 mr-2 text-green-500"></i>
                    <div>
                        <span class="font-medium">处理成功：</span>
                        <span id="base64-success-message"></span>
                    </div>
                </div>
            </div>

            <!-- 文本模式 -->
            <div id="text-mode" class="space-y-6">
                <!-- 输入区域 -->
                <div>
                    <div class="flex items-center justify-between mb-2">
                        <label class="block text-gray-700 text-sm font-bold">
                            输入内容
                        </label>
                        <div class="text-sm text-gray-500">
                            <span id="base64-input-count">0</span> 字符 | 
                            <span id="base64-input-lines">0</span> 行 |
                            <span id="base64-input-size">0 B</span>
                        </div>
                    </div>
                    <div class="relative">
                        <textarea id="base64-input" 
                            class="w-full px-4 py-3 text-gray-700 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 code-editor resize-none" 
                            rows="8" 
                            placeholder="请输入要编码或解码的内容..."></textarea>
                        <button id="paste-base64" class="absolute top-3 right-3 bg-blue-500 hover:bg-blue-600 text-white px-3 py-1 rounded text-sm transition duration-200">
                            粘贴
                        </button>
                    </div>
                </div>

                <!-- 输出区域 -->
                <div>
                    <div class="flex items-center justify-between mb-2">
                        <label class="block text-gray-700 text-sm font-bold">
                            处理结果
                        </label>
                        <div class="text-sm text-gray-500">
                            <span id="base64-output-count">0</span> 字符 | 
                            <span id="base64-output-lines">0</span> 行 |
                            <span id="base64-output-size">0 B</span> |
                            比率: <span id="base64-ratio" class="font-medium text-blue-600">0%</span>
                        </div>
                    </div>
                    <div class="relative">
                        <textarea id="base64-output" 
                            class="w-full px-4 py-3 text-gray-700 border rounded-lg bg-gray-50 code-editor resize-none" 
                            rows="8" 
                            readonly></textarea>
                        <button id="select-all-base64" class="absolute top-3 right-3 bg-gray-500 hover:bg-gray-600 text-white px-3 py-1 rounded text-sm transition duration-200">
                            全选
                        </button>
                    </div>
                </div>
            </div>

            <!-- 文件模式 -->
            <div id="file-mode" class="hidden space-y-6">
                <!-- 文件上传 -->
                <div>
                    <label class="block text-gray-700 text-sm font-bold mb-2">
                        选择文件 (最大 10MB)
                    </label>
                    <div class="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:border-blue-500 transition duration-200">
                        <input type="file" id="file-input" class="hidden" accept="*/*">
                        <div id="file-drop-zone" class="cursor-pointer">
                            <i data-feather="upload-cloud" class="w-12 h-12 mx-auto text-gray-400 mb-4"></i>
                            <p class="text-gray-600 mb-2">点击选择文件或拖拽文件到这里</p>
                            <p class="text-sm text-gray-500">支持所有文件类型</p>
                        </div>
                    </div>
                </div>

                <!-- 文件信息 -->
                <div id="file-info" class="hidden bg-blue-50 border border-blue-200 rounded-lg p-4">
                    <h3 class="text-lg font-semibold text-blue-800 mb-3 flex items-center">
                        <i data-feather="file" class="w-5 h-5 mr-2"></i>
                        文件信息
                    </h3>
                    <div class="grid grid-cols-2 gap-4 text-sm">
                        <div>文件名: <span id="file-name" class="font-medium"></span></div>
                        <div>大小: <span id="file-size" class="font-medium"></span></div>
                        <div>类型: <span id="file-type" class="font-medium"></span></div>
                        <div>修改时间: <span id="file-modified" class="font-medium"></span></div>
                    </div>
                </div>

                <!-- Base64 输出 -->
                <div id="file-base64-output" class="hidden">
                    <div class="flex items-center justify-between mb-2">
                        <label class="block text-gray-700 text-sm font-bold">
                            Base64 编码结果
                        </label>
                        <div class="text-sm text-gray-500">
                            <span id="file-base64-length">0</span> 字符
                        </div>
                    </div>
                    <div class="relative">
                        <textarea id="file-base64-content" 
                            class="w-full px-4 py-3 text-gray-700 border rounded-lg bg-gray-50 code-editor resize-none" 
                            rows="10" 
                            readonly></textarea>
                    </div>
                </div>

                <!-- 解码文件下载 -->
                <div id="decoded-file-download" class="hidden bg-green-50 border border-green-200 rounded-lg p-4">
                    <h3 class="text-lg font-semibold text-green-800 mb-3 flex items-center">
                        <i data-feather="download" class="w-5 h-5 mr-2"></i>
                        解码文件下载
                    </h3>
                    <div class="flex items-center justify-between">
                        <div class="text-sm">
                            <div>文件名: <span id="decoded-file-name" class="font-medium"></span></div>
                            <div>大小: <span id="decoded-file-size" class="font-medium"></span></div>
                        </div>
                        <button id="download-decoded-file" class="bg-green-600 hover:bg-green-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200">
                            下载文件
                        </button>
                    </div>
                </div>
            </div>

            <!-- 使用说明 -->
            <div class="bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200 rounded-lg p-4 mt-6">
                <h3 class="text-lg font-semibold text-blue-800 mb-3 flex items-center">
                    <i data-feather="info" class="w-5 h-5 mr-2"></i>
                    功能说明
                </h3>
                <div class="grid md:grid-cols-2 gap-4 text-sm text-blue-700">
                    <div>
                        <h4 class="font-semibold mb-2">文本处理</h4>
                        <ul class="space-y-1">
                            <li>• 支持中文等Unicode字符编解码</li>
                            <li>• URL安全Base64编码格式</li>
                            <li>• 实时格式验证和统计</li>
                            <li>• 自动填充补齐</li>
                        </ul>
                    </div>
                    <div>
                        <h4 class="font-semibold mb-2">文件处理</h4>
                        <ul class="space-y-1">
                            <li>• 支持任意类型文件编码</li>
                            <li>• 拖拽上传，最大10MB</li>
                            <li>• Base64解码还原文件</li>
                            <li>• 文件信息详细显示</li>
                        </ul>
                    </div>
                </div>
            </div>
        `;
    }

    static init() {
        const base64Input = document.getElementById('base64-input');
        const base64Output = document.getElementById('base64-output');
        const encodeBtn = document.getElementById('encode-base64');
        const decodeBtn = document.getElementById('decode-base64');
        const validateBtn = document.getElementById('validate-base64');
        const clearBtn = document.getElementById('clear-base64');
        const copyBtn = document.getElementById('copy-base64');
        const downloadBtn = document.getElementById('download-base64');
        const pasteBtn = document.getElementById('paste-base64');
        const selectAllBtn = document.getElementById('select-all-base64');
        
        // 模式切换
        const modeRadios = document.querySelectorAll('input[name="base64-mode"]');
        const textMode = document.getElementById('text-mode');
        const fileMode = document.getElementById('file-mode');
        const fileInput = document.getElementById('file-input');
        const fileDropZone = document.getElementById('file-drop-zone');
        
        // 设置控件
        const charsetSelect = document.getElementById('base64-charset');
        const urlSafeCheck = document.getElementById('base64-url-safe');
        const removePaddingCheck = document.getElementById('base64-remove-padding');
        
        // 状态显示
        const statusSpan = document.getElementById('base64-status');
        const errorDiv = document.getElementById('base64-error');
        const successDiv = document.getElementById('base64-success');
        const errorMessage = document.getElementById('base64-error-message');
        const successMessage = document.getElementById('base64-success-message');
        
        // 文件相关元素
        const fileInfo = document.getElementById('file-info');
        const fileBase64Output = document.getElementById('file-base64-output');
        const fileBase64Content = document.getElementById('file-base64-content');
        const decodedFileDownload = document.getElementById('decoded-file-download');

        let currentOutput = '';
        let currentFile = null;

        // 更新状态显示
        const updateStatus = (status) => {
            statusSpan.textContent = status;
        };

        // 显示成功消息
        const showSuccess = (message) => {
            successMessage.textContent = message;
            successDiv.classList.remove('hidden');
            errorDiv.classList.add('hidden');
            setTimeout(() => {
                successDiv.classList.add('hidden');
            }, 3000);
        };

        // 显示错误消息
        const showError = (message) => {
            errorMessage.textContent = message;
            errorDiv.classList.remove('hidden');
            successDiv.classList.add('hidden');
        };

        // 隐藏所有提示
        const hideMessages = () => {
            errorDiv.classList.add('hidden');
            successDiv.classList.add('hidden');
        };

        // 统计信息更新
        const updateStats = () => {
            const lines = base64Input.value.split('\n').length;
            const size = new Blob([base64Input.value]).size;
            
            document.getElementById('base64-input-count').textContent = base64Input.value.length;
            document.getElementById('base64-input-lines').textContent = lines;
            document.getElementById('base64-input-size').textContent = DevToolsUtils.formatFileSize(size);

            if (currentOutput) {
                const outputLines = currentOutput.split('\n').length;
                const outputSize = new Blob([currentOutput]).size;
                
                document.getElementById('base64-output-count').textContent = currentOutput.length;
                document.getElementById('base64-output-lines').textContent = outputLines;
                document.getElementById('base64-output-size').textContent = DevToolsUtils.formatFileSize(outputSize);
                
                const ratio = base64Input.value.length > 0 ? 
                    ((currentOutput.length / base64Input.value.length) * 100).toFixed(1) : '0';
                document.getElementById('base64-ratio').textContent = ratio + '%';
            } else {
                document.getElementById('base64-output-count').textContent = '0';
                document.getElementById('base64-output-lines').textContent = '0';
                document.getElementById('base64-output-size').textContent = '0 B';
                document.getElementById('base64-ratio').textContent = '0%';
            }
        };

        // 模式切换
        modeRadios.forEach(radio => {
            radio.addEventListener('change', () => {
                if (radio.value === 'text') {
                    textMode.classList.remove('hidden');
                    fileMode.classList.add('hidden');
                    updateStatus('文本模式');
                } else {
                    textMode.classList.add('hidden');
                    fileMode.classList.remove('hidden');
                    updateStatus('文件模式');
                }
                hideMessages();
            });
        });

        // 输入事件监听
        base64Input.addEventListener('input', DevToolsUtils.debounce(() => {
            updateStats();
            updateStatus('输入中...');
            
            // 实时验证
            if (base64Input.value.trim()) {
                const urlSafe = urlSafeCheck.checked;
                const result = Base64Encoder.validate(base64Input.value, { urlSafe });
                if (result.success) {
                    DevToolsUtils.removeStatusBorder(base64Input);
                    updateStatus('格式正确');
                } else {
                    DevToolsUtils.addErrorBorder(base64Input);
                    updateStatus('格式可能有误');
                }
            } else {
                DevToolsUtils.removeStatusBorder(base64Input);
                updateStatus('就绪');
            }
        }, 500));

        // 编码按钮
        encodeBtn.addEventListener('click', () => {
            DevToolsUtils.addLoading(encodeBtn);
            hideMessages();
            updateStatus('编码中...');
            
            setTimeout(() => {
                const charset = charsetSelect.value;
                const urlSafe = urlSafeCheck.checked;
                const removePadding = removePaddingCheck.checked;
                
                const result = Base64Encoder.encode(base64Input.value, {
                    charset,
                    urlSafe,
                    removePadding
                });
                
                if (result.success) {
                    currentOutput = result.data;
                    base64Output.value = result.data;
                    DevToolsUtils.addSuccessBorder(base64Input);
                    showSuccess(`编码完成，原文 ${result.originalLength} 字符，编码后 ${result.encodedLength} 字符`);
                    updateStatus('编码完成');
                } else {
                    showError(result.error);
                    DevToolsUtils.addErrorBorder(base64Input);
                    updateStatus('编码失败');
                }
                
                updateStats();
                DevToolsUtils.removeLoading(encodeBtn);
                
                setTimeout(() => {
                    if (typeof feather !== 'undefined') {
                        feather.replace();
                    }
                }, 100);
            }, 200);
        });

        // 解码按钮
        decodeBtn.addEventListener('click', () => {
            DevToolsUtils.addLoading(decodeBtn);
            hideMessages();
            updateStatus('解码中...');
            
            setTimeout(() => {
                const charset = charsetSelect.value;
                const urlSafe = urlSafeCheck.checked;
                
                const result = Base64Encoder.decode(base64Input.value, {
                    charset,
                    urlSafe
                });
                
                if (result.success) {
                    currentOutput = result.data;
                    base64Output.value = result.data;
                    DevToolsUtils.addSuccessBorder(base64Input);
                    showSuccess(`解码完成，编码长度 ${result.originalLength} 字符，解码后 ${result.decodedLength} 字符`);
                    updateStatus('解码完成');
                } else {
                    showError(result.error);
                    DevToolsUtils.addErrorBorder(base64Input);
                    updateStatus('解码失败');
                }
                
                updateStats();
                DevToolsUtils.removeLoading(decodeBtn);
                
                setTimeout(() => {
                    if (typeof feather !== 'undefined') {
                        feather.replace();
                    }
                }, 100);
            }, 200);
        });

        // 验证按钮
        validateBtn.addEventListener('click', () => {
            DevToolsUtils.addLoading(validateBtn);
            hideMessages();
            updateStatus('验证中...');
            
            setTimeout(() => {
                const urlSafe = urlSafeCheck.checked;
                const result = Base64Encoder.validate(base64Input.value, { urlSafe });
                
                if (result.success) {
                    DevToolsUtils.addSuccessBorder(base64Input);
                    const data = result.data;
                    showSuccess(`Base64格式正确！长度: ${data.length}, 包含URL安全字符: ${data.hasUrlSafeChars ? '是' : '否'}, 填充: ${data.hasPadding ? data.paddingLength + '个' : '无'}`);
                    updateStatus('验证通过');
                } else {
                    showError(result.error);
                    DevToolsUtils.addErrorBorder(base64Input);
                    updateStatus('验证失败');
                }
                
                DevToolsUtils.removeLoading(validateBtn);
                
                setTimeout(() => {
                    if (typeof feather !== 'undefined') {
                        feather.replace();
                    }
                }, 100);
            }, 200);
        });

        // 清空按钮
        clearBtn.addEventListener('click', () => {
            base64Input.value = '';
            base64Output.value = '';
            currentOutput = '';
            currentFile = null;
            hideMessages();
            DevToolsUtils.removeStatusBorder(base64Input);
            
            // 隐藏文件相关UI
            fileInfo.classList.add('hidden');
            fileBase64Output.classList.add('hidden');
            decodedFileDownload.classList.add('hidden');
            
            updateStats();
            updateStatus('就绪');
        });

        // 复制按钮
        copyBtn.addEventListener('click', async () => {
            if (currentOutput) {
                await DevToolsUtils.copyToClipboard(currentOutput);
                DevToolsUtils.showToast('已复制到剪贴板！');
            } else {
                DevToolsUtils.showToast('没有可复制的内容', 'error');
            }
        });

        // 下载按钮
        downloadBtn.addEventListener('click', () => {
            if (currentOutput) {
                const filename = prompt('输入文件名:', 'base64_result.txt') || 'base64_result.txt';
                DevToolsUtils.downloadFile(currentOutput, filename, 'text/plain');
                DevToolsUtils.showToast('文件下载成功！');
            } else {
                DevToolsUtils.showToast('没有可下载的内容', 'error');
            }
        });

        // 粘贴按钮
        pasteBtn.addEventListener('click', async () => {
            try {
                const text = await navigator.clipboard.readText();
                base64Input.value = text;
                updateStats();
                DevToolsUtils.showToast('粘贴成功！');
            } catch (err) {
                DevToolsUtils.showToast('粘贴失败，请手动粘贴', 'error');
            }
        });

        // 全选输出按钮
        selectAllBtn.addEventListener('click', () => {
            base64Output.select();
            DevToolsUtils.showToast('已全选输出内容！');
        });

        // 文件处理
        const handleFile = async (file) => {
            if (!file) return;
            
            currentFile = file;
            updateStatus('处理文件中...');
            
            const result = await Base64Encoder.encodeFile(file);
            if (result.success) {
                // 显示文件信息
                document.getElementById('file-name').textContent = result.fileInfo.name;
                document.getElementById('file-size').textContent = DevToolsUtils.formatFileSize(result.fileInfo.size);
                document.getElementById('file-type').textContent = result.fileInfo.type || '未知';
                document.getElementById('file-modified').textContent = result.fileInfo.lastModified;
                
                // 显示Base64结果
                fileBase64Content.value = result.data;
                document.getElementById('file-base64-length').textContent = result.data.length;
                
                fileInfo.classList.remove('hidden');
                fileBase64Output.classList.remove('hidden');
                
                currentOutput = result.data;
                showSuccess(`文件编码完成，共 ${result.data.length} 字符`);
                updateStatus('文件编码完成');
            } else {
                showError(result.error);
                updateStatus('文件处理失败');
            }
            
            setTimeout(() => {
                if (typeof feather !== 'undefined') {
                    feather.replace();
                }
            }, 100);
        };

        // 文件拖拽
        fileDropZone.addEventListener('click', () => {
            fileInput.click();
        });

        fileDropZone.addEventListener('dragover', (e) => {
            e.preventDefault();
            fileDropZone.classList.add('border-blue-500');
        });

        fileDropZone.addEventListener('dragleave', () => {
            fileDropZone.classList.remove('border-blue-500');
        });

        fileDropZone.addEventListener('drop', (e) => {
            e.preventDefault();
            fileDropZone.classList.remove('border-blue-500');
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                handleFile(files[0]);
            }
        });

        fileInput.addEventListener('change', (e) => {
            if (e.target.files.length > 0) {
                handleFile(e.target.files[0]);
            }
        });

        // 初始化
        updateStats();
        updateStatus('就绪');
        
        // 刷新图标
        setTimeout(() => {
            if (typeof feather !== 'undefined') {
                feather.replace();
            }
        }, 100);
    }
};